package com.wwj.auction.login.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.auction.login.entity.TransFlow;
import com.wwj.auction.login.entity.UserAccount;
import com.wwj.auction.login.entity.to.UserInfoTo;
import com.wwj.auction.login.entity.vo.TransFlowVo;
import com.wwj.auction.login.enums.TransFlowType;
import com.wwj.auction.login.mapper.TransFlowMapper;
import com.wwj.auction.login.mapper.UserAccountMapper;
import com.wwj.auction.login.service.TransFlowService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wwj
 * @since 2021-08-10
 */
@Service
public class TransFlowServiceImpl extends ServiceImpl<TransFlowMapper, TransFlow> implements TransFlowService {

    @Resource
    private UserAccountMapper userAccountMapper;

    @Override
    public void savePay(Map<String, String[]> parameterMap, UserInfoTo userInfoTo) {
        // 获取支付金额
        String totalAmounts = parameterMap.get("total_amount")[0];
        // 获取交易单号
        String outTradeNo = parameterMap.get("out_trade_no")[0];
        // 获取订单创建时间
        String gmtPayment = parameterMap.get("gmt_payment")[0];
        // 封装交易流水
        TransFlow transFlow = new TransFlow();
        transFlow.setTransAmount(new BigDecimal(totalAmounts));
        transFlow.setTransNo(outTradeNo);
        // 转换时间
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.parse(gmtPayment, dateTimeFormatter);
        transFlow.setCreateTime(localDateTime);
        // 得到交易类型
        Integer type = userInfoTo.getType();
        transFlow.setTransType(type);
        if (TransFlowType.TOP_UP.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.TOP_UP.getMsg());
            // 若交易类型为充值，则修改当前用户的账户金额
            Integer userId = userInfoTo.getId();
            // 设置用户id
            transFlow.setUserId(userId);
            // 通过userid查询当前用户的账户信息
            UserAccount userAccount = userAccountMapper.selectOne(
                    new LambdaQueryWrapper<UserAccount>()
                            .eq(UserAccount::getUserId, userId));
            // 原金额加上充值的金额
            BigDecimal finalAmount = userAccount.getAmount().add(new BigDecimal(totalAmounts));
            userAccount.setAmount(finalAmount);
            // 更新账户
            userAccountMapper.updateById(userAccount);
        } else if (TransFlowType.WITHDRAW_DEPOSIT.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.WITHDRAW_DEPOSIT.getMsg());
        } else if (TransFlowType.BUY_GOODS.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.BUY_GOODS.getMsg());
        } else if (TransFlowType.TO_SELL.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.TO_SELL.getMsg());
        }
        // 保存支付信息
        baseMapper.insert(transFlow);
    }

    @Override
    public List<TransFlowVo> listForTransFlowVo(Integer userId) {
        // 通过userId查询到当前用户的交易流水
        List<TransFlow> transFlowList = baseMapper.selectList(
                Wrappers.lambdaQuery(TransFlow.class)
                        .eq(TransFlow::getUserId, userId)
                        .orderByDesc(TransFlow::getId));
        List<TransFlowVo> transFlowVoList = transFlowList.stream().map(transFlow -> {
            TransFlowVo transFlowVo = new TransFlowVo();
            // 属性拷贝
            BeanUtils.copyProperties(transFlow, transFlowVo);
            // 格式化交易时间
            LocalDateTime localDateTime = transFlow.getCreateTime();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String time = localDateTime.format(dateTimeFormatter);
            transFlowVo.setCreateTime(time);
            return transFlowVo;
        }).collect(Collectors.toList());
        return transFlowVoList;
    }

    @Override
    public void saveFlow(Integer userId, String fetchAmt) {
        // 封装交易流水
        TransFlow transFlow = new TransFlow();
        transFlow.setUserId(userId);
        String transNo = UUID.randomUUID().toString().replaceAll("-", "");
        transFlow.setTransNo(transNo);
        transFlow.setTransType(TransFlowType.FREEZE.getStatus());
        transFlow.setTransTypeName(TransFlowType.FREEZE.getMsg());
        transFlow.setTransAmount(new BigDecimal(fetchAmt));
        transFlow.setCreateTime(LocalDateTime.now());
        // 保存
        baseMapper.insert(transFlow);
    }

    @Override
    public void addAmount(UserInfoTo userInfoTo) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取支付金额
        String totalAmounts = userInfoTo.getAmounts();
        // 获取交易单号
        String outTradeNo = UUID.randomUUID().toString();
        // 获取订单创建时间
        String gmtPayment = LocalDateTime.now().format(dateTimeFormatter);
        // 封装交易流水
        TransFlow transFlow = new TransFlow();
        transFlow.setTransAmount(new BigDecimal(totalAmounts));
        transFlow.setTransNo(outTradeNo);
        // 转换时间
        LocalDateTime localDateTime = LocalDateTime.parse(gmtPayment, dateTimeFormatter);
        transFlow.setCreateTime(localDateTime);
        // 得到交易类型
        Integer type = userInfoTo.getType();
        transFlow.setTransType(type);
        if (TransFlowType.TOP_UP.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.TOP_UP.getMsg());
            // 若交易类型为充值，则修改当前用户的账户金额
            Integer userId = userInfoTo.getId();
            // 设置用户id
            transFlow.setUserId(userId);
            // 通过userid查询当前用户的账户信息
            UserAccount userAccount = userAccountMapper.selectOne(
                    new LambdaQueryWrapper<UserAccount>()
                            .eq(UserAccount::getUserId, userId));
            // 原金额加上充值的金额
            BigDecimal finalAmount = userAccount.getAmount().add(new BigDecimal(totalAmounts));
            userAccount.setAmount(finalAmount);
            // 更新账户
            userAccountMapper.updateById(userAccount);
        } else if (TransFlowType.WITHDRAW_DEPOSIT.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.WITHDRAW_DEPOSIT.getMsg());
        } else if (TransFlowType.BUY_GOODS.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.BUY_GOODS.getMsg());
        } else if (TransFlowType.TO_SELL.getStatus().equals(type)) {
            transFlow.setTransTypeName(TransFlowType.TO_SELL.getMsg());
        }
        // 保存支付信息
        baseMapper.insert(transFlow);
    }
}
